<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

defineOptions({ name: '药品' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({
  show0: true
})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  data_ini:{
    type: [],
    category_id:[]
  },
  config:[],
  drugs_use:[],
  drawerVisible:false,
  search_uid:0,
  keyword_use:'',

})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '药品',
  initForm: {},
  doCreate: api.createDrugs,
  doUpdate: api.updateDrugs,
  doDelete: api.deleteDrugs,
  refresh: () => $table.value?.handlerefresh(),
})
const datetimeRange = ref()

onMounted(() => {
  $table.value?.handleSearch()
  api.getConfig().then((res) => {
    data.config = res.data
  })
})

const drugsUseColumns = [
  {
    title: '客户',
    key: 'receive_user',
    width: 120,
    align: 'center'
  },
  {
    title: '使用数量',
    key: 'total_number',
    width: 80,
    align: 'center'
  },
  {
    title: '使用时间',
    key: 'add_time',
    width: 80,
    align: 'center'
  },
    {
    title: '批号',
    key: 'batch',
    width: 80,
    align: 'center'
  },
  {
    title: '单价',
    key: 'unit_price',
    width: 80,
    align: 'center'
  },
  {
    title: '总价',
    key: 'total_price',
    width: 80,
    align: 'center'
  },
    {
    title: '有效期',
    key: 'valid_at',
    width: 80,
    align: 'center'
  },
]

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '分类',
    key: 'category_name',
    width: 40,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.category_name })
    },
  },
    {
    title: '图片/项目名称',
    key: 'image',
    width: 170,
    align: 'left',
    render(row) {
      return h(NFlex, {},
        [h(NAvatar, {
          src: row.image,
          fallbackSrc: default_image,
          round: true,
          size: "medium",
        }), h(NButton, {
          size: "medium",
          dashed: true,
          type: "primary",
        }, {
          default: () => (row.name)
        })]
      )

    },
  },
  {
    title: '规格',
    key: 'spec',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '单位',
    key: 'unit',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '价格',
    key: 'drug_price',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '当前库存',
    key: 'all_nums',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '当前金额',
    key: 'all_price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },


  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
          withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_detail(row)
              },
            },
            {
              default: () => '使用情况',
              icon: renderIcon('material-symbols:search', { size: 16 }),
            }
          ),
          []
        ),
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                on_edit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]



const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}


function on_add(){
  handleAdd()
}

function on_edit(row){
  handleEdit(row)
}

function on_detail(row) {
  data.search_uid = row.id
  api.getDrugsUse({
    id: row.id,
  }).then((res) => {
    data.drugs_use = res.data
    data.drawerVisible = true // 获取数据后显示右弹窗
  })
}

function on_search() {
  const keyword = data.keyword_use;

  if(keyword==='' && datetimeRange.value===undefined){
    api.getDrugsUse({
      id: data.search_uid,
    }).then((res) => {
      data.drugs_use = res.data
      data.drawerVisible = true // 获取数据后显示右弹窗
    })
  }

  let drugs_filter = data.drugs_use.filter(item =>
    item.receive_user?.includes(keyword)
  );

  if(datetimeRange.value){
      const start = datetimeRange.value[0];
      const end = datetimeRange.value[1];
      drugs_filter = drugs_filter.filter(item => {
          const timestamp = new Date(item.add_time).getTime(); // 转换为秒级时间戳
          return timestamp >= start&& timestamp <= end
      })
  }
  data.drugs_use = drugs_filter
}

</script>

<template>
  <NLayout has-sider wh-full style="margin-top: 10px">
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer>
        <template  #action>
          <NButton type="primary" @click="on_add" >
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建{{ nameFromInstance }}
          </NButton>
        </template>

        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getDrugsList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem :label="nameFromInstance+'名称'" :label-width="80">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="空库存显示" style="line-height: 30px" :label-width="100">
              <n-switch size="large" v-model:value="queryItems.show0" @update:value="$table?.handleSearch()" />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 800px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >

                <NFormItem label="分类" path="category_id">
                  <n-select
                    v-model:value="modalForm.category_id"
                    :options="data.config.drugscategory"
                    placeholder="请选择类型"
                    label-field="name"
                    value-field="id"
                  />
                </NFormItem>
                <NFormItem label="名称" path="name">
                  <NInput v-model:value="modalForm.name" clearable placeholder="请输入名称" />
                </NFormItem>
                <NFormItem label="规格" path="spec">
                  <NInput   style="width: 100%"   v-model:value="modalForm.spec" placeholder="请输入规格" />
                </NFormItem>
                <NFormItem label="单位" path="unit">
                  <NInput   style="width: 100%"   v-model:value="modalForm.unit" placeholder="请输入单位" />
                </NFormItem>
                <NFormItem label="价格" path="drug_price">
                  <NInput   style="width: 100%"   v-model:value="modalForm.drug_price" placeholder="请输入单位" />
                </NFormItem>
                <NFormItem label="批准文号" path="approval_number">
                  <NInput   style="width: 100%"   v-model:value="modalForm.approval_number" placeholder="请输入批准文字号" />
                </NFormItem>
                <NFormItem label="排序" path="sort">
                  <NInputNumber  min="0" style="width: 100%"   v-model:value="modalForm.sort" placeholder="请输入排序" />
                </NFormItem>

          </NForm>
        </CrudModal>
      </CommonPage>
      <NDrawer
    v-model:show="data.drawerVisible"
    :width="800"
    placement="right"
    resizable
  >
    <NDrawerContent title="使用情况" closable>
      <div style="display: flex;margin: 20px">
        <NInput v-model:value="data.keyword_use" :loading="data.loading" clearable
                type="text" placeholder="请输入客户姓名检索" style="margin-right: 5px;width: 300px"/>
        <NDatePicker
            v-model:value="datetimeRange"
            type="datetimerange"
            clearable
            placeholder="请选择时间范围"
        />
        <n-button type="primary" @click="on_search()">
          <TheIcon icon="material-symbols:manage-search" :size="18" class="mr-5"/>
          搜索
        </n-button>
      </div>
      <NDataTable
        :columns="drugsUseColumns"
        :data="data.drugs_use"
        :bordered="true"
        :striped="true"
        size="small"
        style="margin-bottom: 20px;"
      />
    </NDrawerContent>
  </NDrawer>
    </NLayoutContent>
  </NLayout>

  <!-- 业务页面 -->
</template>
